/*
 * @Author: zhangyang
 * @Date: 2022-02-24 19:21:36
 * @LastEditTime: 2022-02-26 16:21:13
 * @Description: 权限控制
 */
import type { YoungModule } from '../types';
import router from '../route';
import commonRoutes from '../route/common/index';

import { getToken } from '../store';
import type { RouteLocationNormalized } from 'vue-router';

import { storeToRefs } from 'pinia';
import { useUserStore } from './../store/useUserStore';

const getCommonRoutes = () => {
  const routesArr: string[] = [];
  for (const route of commonRoutes) {
    if (route.children?.length) {
      for (const sub of route.children) {
        routesArr.push(sub.path);
      }
    } else {
      routesArr.push(route.path);
    }
  }
  return routesArr;
};

export const hasPermission = (route: RouteLocationNormalized | string) => {
  const { RoleRoute } = storeToRefs(useUserStore());

  const roleRoute = RoleRoute.value.concat(getCommonRoutes());
  if (typeof route === 'string') {
    return roleRoute.includes(route);
  }
  return roleRoute.includes(route.path) || roleRoute.includes(route.fullPath);
};

const checkNavData = async () => {
  const { generateUserInfo } = await import('../util/generateUserInfo');
  const { NavArr } = storeToRefs(useUserStore());

  if (NavArr.value.length === 0) {
    await generateUserInfo();
  }
};

export const install: YoungModule = (app) => {
  router.beforeEach(async (to, from, next) => {
    document.title = (to.meta.title as string) || '小黑后台';

    // 此处添加鉴权
    if (!getToken().token && to.name !== 'login') {
      await ElMessageBox.confirm('未登录或登录信息过期，请先去登录', '提示', {
        type: 'error',
        showCancelButton: false,
        closeOnClickModal: false,
      }).catch(() => null);
      next({
        name: 'login',
        query: {
          redirect: to.path,
        },
      });
    } else if (!hasPermission(to)) {
      // 具体页面权限 map 判断
      ElMessage.error('暂时无权访问该页面，请勿进行恶意操作');
      next(from.path);
    } else {
      // 如果没有节点数据则重新生成
      await checkNavData();
      next();
    }
  });
};
